package com.xuelang.pipeline.app.resource.impl;

import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
import java.lang.RuntimeException;
import java.util.concurrent.TimeoutException;
import com.xuelang.pipeline.app.resource.ArtifactToolService;
import com.xuelang.pipeline.app.resource.request.ArtifactToolQuery;
import com.xuelang.pipeline.client.common.result.ApiResult;
import com.xuelang.pipeline.client.resource.dto.ArtifactToolDTO;
import org.springframework.cloud.openfeign.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liuyuan.ly
 * @since 2024/8/16 16:05
 */
@Service
@Slf4j
public class ArtifactToolServiceFallbackImpl implements FallbackFactory<ArtifactToolService> {
    @Override
    public ArtifactToolService create(Throwable throwable) {
        String fallReason = throwable.getMessage();
        if (throwable instanceof TimeoutException) {
            fallReason = "Socket connect timeout.";
        } else if (throwable instanceof NoFallbackAvailableException) {
            fallReason = "Bad Request.";
        } else if (throwable instanceof RuntimeException) {
            fallReason = "Runtime exception";
        }
        final String returnFallReason = fallReason;
        log.error("调用fegin数据接口失败。接口名称:{}；失败原因:{}", this.getClass().getName(), fallReason);
        return new ArtifactToolService() {
            ApiResult apiResult = ApiResult.fail("worker返回异常：" + returnFallReason);

            @Override
            public ApiResult<ArtifactToolDTO> queryArtifactTool(String artifactToolUuid) {
                return apiResult;
            }

            @Override
            public ApiResult<List<ArtifactToolDTO>> withoutDataArtifactToolList(String artifactType) {
                return apiResult;
            }

            @Override
            public ApiResult<List<ArtifactToolDTO>> conditionalArtifactToolList(ArtifactToolQuery artifactToolQuery) {
                return apiResult;
            }
        };
    }
}
